/* eslint-disable consistent-return */
/* eslint-disable no-shadow */
/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
import React from 'react';
import { connect } from 'dva';
import { DownloadOutlined, DownOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import {
  Card,
  Button,
  Form,
  Input,
  Table,
  Select,
  message,
  Row,
  Col,
  Tabs,
  Modal,
  Badge,
  Spin,
  Checkbox,
  Divider,
  Dropdown,
  Menu,
  Timeline,
  Radio,
} from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile from '@/utils/utils'; // 导出excel
import { matchDict, getcheckboxList } from '@/utils/utils';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import SearchPersonEs from '../../components/SearchPersonEs';
import TextOverFlow from '../../components/TextOverFlow';
import Customer from '../../components/CustomerWithState'; // 获取字典客户名称

const { Option } = Select;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;
const { confirm } = Modal;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { TextArea } = Input;

@connect(({ login: { systemList } }) => ({
  sysCode: (systemList.length && systemList[0].sysCode) || 1,
}))
@connect(({ publicdata, laborcontract, loading, login }) => ({
  dictCode: publicdata.dictCode,
  loading: loading.models.laborcontract,
  formFieldsValue: laborcontract.formFieldsValue,
  expandForm: laborcontract.expandForm,
  activeKey: laborcontract.activeKey,
  pageData: laborcontract.pageData,
  login,
  valuesArr: laborcontract.valuesArr,
}))
class BasicList extends React.Component {
  formRef = React.createRef()

  constructor(props) {
    super(props);
    this.state = {
      isCsweb: true, // 是否是客服系统
      selectedRowKeys: [],
      selectedRows: [],
      formValues: {},
      tabList: [{ name: '待签订' }, { name: '已签订' }, { name: '已终止' }],
      stateMap: ['error', 'default', 'warning', 'success'],
      issFlagMap: ['default', 'success', 'warning', 'error'],
      stepsList: [], // 办理备注历史记录
      busiId: '', // 办理备注劳动合同ID
      MAIL_OBJ: [], // 发放对象
      signMethod: '1', // 发放方式开关
      labourList: [], // 发放方式
      CONT_SIGN_WAY: [], // 劳动合同签署方式
      LABOUR_CONT_STATE: [], // 劳动合同状态
    };
    // 表单布局
    this.formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 17 },
    };
  }

  componentDidMount = () => {
    this.getCurrentSystem();
    const {
      dispatch,
    } = this.props;
    // 获取字典状态
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: [
        'ADD_ID_TYPE',
        'SIGN_TYPE',
        'CONT_SIGN_WAY',
        'YES_NO_FLAG',
        'MAIL_OBJ',
        'LABOUR_SIGN_WAY',
        'LABOUR_CONT_STATE',
      ],
    }).then(dictCode => {
      this.setState({
        MAIL_OBJ: dictCode && dictCode.MAIL_OBJ,
        labourList: dictCode && dictCode.LABOUR_SIGN_WAY,
        CONT_SIGN_WAY: dictCode && dictCode.CONT_SIGN_WAY,
        LABOUR_CONT_STATE: dictCode && dictCode.LABOUR_CONT_STATE,
      });
    });
    this.getInitialList();
  };

  /**
   * 获取当前系统
   */
  getCurrentSystem = () => {
    const { login:{ systemList } } = this.props;
    let sysCode;
    if(systemList.length){
      systemList.forEach(item=>{
          if(item.isSelected){
              sysCode = item.sysCode
          }
      })
    }
    this.setState({
      isCsweb : sysCode === 1
    })
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      if (location.queryParam && location.queryParam.certNo) {
        location.queryParam.cardNo = location.queryParam.certNo;
      }
      dispatch({
        type: 'laborcontract/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'laborcontract/updateModelData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = async activeKey => {
    const { valuesArr, dispatch } = this.props;
    const values = await this.formRef.current.validateFields(valuesArr);
    await dispatch({
      type: 'laborcontract/updateModelData',
      payload: {
        formFieldsValue: values,
        activeKey,
      },
    });
    this.searchList(this.processFormData(values), activeKey);
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    issFlag,
    isClear = true,
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      laborContTab: activeKey,
      pagerArg,
      issFlag,
    };

    dispatch({
      type: 'laborcontract/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'laborcontract/fetchList',
      payload: values,
    });

    this.setState({
      formValues: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'empName' || key === 'cardNo') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] = tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
    });
    return formFieldsValue;
  };

  // 重置
  resetSearch = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'laborcontract/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    this.state.selectedRowKeys = [];
    this.state.selectedRows = [];
  };

  // 展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'laborcontract/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { dispatch, location, formFieldsValue } = this.props;
    // 更改当前models里面state的数据
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    dispatch({
      type: 'laborcontract/updateModelData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        }
      },
    });
    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  // 导出
  export = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length) {
      this.exportExcel();
    } else {
      confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '请选择一条合同数据，如不选择，默认导出当前条件下所有数据！',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    }
  };

  // 导出表格
  exportExcel = () => {
    const { selectedRowKeys, formValues } = this.state;
    const { activeKey } = this.props;
    delete formValues.pagerArg;
    const params = {
      ...formValues,
      laborContIds: selectedRowKeys,
      laborContTab: activeKey,
    };
    downloadFile(params, '/csApi/laborCont/getExportList', 'POST');
  };

  // 办理备注(获取)
  handleRemarks = busiId => {
    this.setState({ busiId });
    this.remarksModal(true);
    const { dispatch } = this.props;
    dispatch({
      type: 'laborcontract/getRemark',
      payload: { busiId },
    }).then(response => {
      if (response.success) {
        this.setState({ stepsList: response.data || [] });
      } else {
        message.warning(`${response.message || '办理备注：服务器端错误！'}`);
      }
    });
  };

  // 办理备注(提交)
  submitDataRemark = async () => {
    const { busiId } = this.state;
    const { dispatch } = this.props;
    const values = await this.formRef.current.validateFields()
    const res = await dispatch({
      type: 'laborcontract/remarkSubmit',
      payload: {
        busiId,
        content: values.content,
      },
    });
    if (res.success) {
      message.success('添加成功！');
      this.setState({ modalVisibleRemark: false });
      this.formRef.current.resetFields(['content']);
    } else {
      message.warning(`${res.message || '提交数据：服务器端错误！'}`);
    }
  };

  // 发放的提交
  submitData = async () => {
    const {
      pageData: { pagination },
      activeKey,
      dispatch,
      formFieldsValue,
    } = this.props;
    const values = await this.formRef.current.validateFields();
    const { selectedRows } = this.state;
    const laborConts = [];
    selectedRows.map((item) => {
      laborConts.push({
        laborContId: item.laborContId,
        vno: item.vno,
      });
    });
    const params = {
      laborConts, // 选中的数据
      issObjs: values.respDepId, // 发放对象集合
      issWay: values.issWay, // 发放方式
      exprsNo: values.exprsNo || '', // 快递单号
      issRemark: values.issRemark || '', // 备注
    };
    const res = await dispatch({
      type: 'laborcontract/updateIssFlag',
      payload: params,
    });
    if (res.success) {
      if (res.data) {
        this.formRef.current.resetFields(['respDepId', 'issRemark', 'issRemark', 'exprsNo']);
        message.warning(`${res.data || '服务器端错误'}`);
        this.setState({ selectedRowKeys: [], modalVisible: false });
        this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
      } else {
        this.formRef.current.resetFields(['respDepId', 'issRemark', 'issRemark', 'exprsNo']);
        message.warning(`${res.data || '服务器端错误'}`);
        this.setState({ selectedRowKeys: [], modalVisible: false });
        this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
      }
    } else {
      message.warning(`${res.message || '发放失败：服务器端错误！'}`);
    }
  };

  // 切换模态框(办理备注)
  remarksModal = flag => {
    this.setState({
      modalVisibleRemark: !!flag,
    });
  };

  // 发放
  sendCont = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length) {
      this.sendContModal(true);
    } else {
      message.warning('请选择至少一条数据！');
    }
  };

  // 切换模态框(发放合同)
  sendContModal = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  // 发放方式
  changeSignMethod = e => {
    this.setState({ signMethod: e.target.value });
  };

  // 终止
  termination = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    const { dispatch } = this.props;
    const list = [];
    selectedRows.map(item => {
      list.push({
        laborContId: item.laborContId,
        vno: item.vno,
      });
    });
    if (selectedRowKeys.length > 0) {
      dispatch({
        type: 'laborcontract/updateEndLabor',
        payload: {
          list,
        },
      }).then(response => {
        if (response.success && response.data !== '') {
          message.warning(response.data || '终止失败！');
          this.setState({ selectedRowKeys: [] });
        } else if (response.success && response.data === '') {
          message.success('终止成功！');
          this.setState({ selectedRowKeys: [] });
          this.changeTabPane('3');
        } else {
          message.warning(`${response.message || '终止失败：服务器端错误！'}`);
        }
      });
    } else {
      message.warning('请选择至少一条数据！');
    }
  };

  // 全部,已发放，未发放
  searchAll = e => {
    const {
      pageData: { pagination },
      activeKey,
      formFieldsValue,
    } = this.props;
    this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize, e.target.value);
  };

  // 是否进入签订页面
  isSignPage = record => {
    const { location: { pathname } } = this.props;
    const tempUrl = pathname.split('/index')[0];
    const { activeKey, login } = this.props;
    if (
      (record.contSignWay === 3 && login.systemList[0].sysCode === 1) ||
      (record.contSignWay === 1 && login.systemList[0].sysCode === 3)
    ) {
      confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: `此合同的签署方是${record.contSignWayName}，是否继续？`,
        okText: '继续',
        cancelText: '取消',
        onOk() {
          router.push(
            `${tempUrl}/sign?laborContId=${record.laborContId}&empId=${record.empId}&custId=${
              record.custId
            }&activeKey=${activeKey}`
          );
        },
      });
    } else {
      router.push(
        `${tempUrl}/sign?laborContId=${record.laborContId}&empId=${record.empId}&custId=${
          record.custId
        }&activeKey=${activeKey}`
      );
    }
  };

  // 合同状态的排序处理
  onWaitForSignContChange = (pagination, filters, sorter) => {
    const { formValues } = this.state;
    const { activeKey, dispatch } = this.props;
    const pagerArg = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    const values = {
      ...formValues,
      laborContTab: activeKey,
      pagerArg,
    };
    // 列表有排序的字段处理
    if (sorter.field) {
      let sortBy = '';
      if (sorter.order === 'ascend') {
        sortBy = 'ASC';
      } else {
        sortBy = 'DESC';
      }
      values.pageOrdBys = []; // 排序集合
      values.pageOrdBys.push({
        property: 'contState',
        ordBy: sortBy,
      });
    }
    dispatch({
      type: 'laborcontract/fetchList',
      payload: values,
    });
  };

  renderSimpleForm() {
    const {
      formFieldsValue,
      activeKey,
    } = this.props;
    return (
      <Form layout="inline" ref={this.formRef} initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="姓名" name="empName">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="证件号" name="cardNo">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      formFieldsValue,
      activeKey,
    } = this.props;
    const { CONT_SIGN_WAY, LABOUR_CONT_STATE, isCsweb } = this.state;
    return (
      <Form layout="inline" ref={this.formRef} initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="姓名" name="empName">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="证件号" name="cardNo">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="客户名称" name="custId">
              { isCsweb ? <Customer allowClear /> : <Customer attr allowClear /> }
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="办理人" {...this.formItemLayout} name="tskId">
              <SearchPersonEs
                allowClear
                showSearch
                filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="合同签署方" name="contSignWay">
              <HOCSelect placeholder="请选择" allowClear>
                {CONT_SIGN_WAY.map(item => (
                  <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
              </HOCSelect>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="合同状态" name="contState">
              <HOCSelect placeholder="请选择" allowClear>
                {LABOUR_CONT_STATE.map(item => (
                  <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
              </HOCSelect>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { location: { pathname } }  = this.props;
    const tempUrl = pathname.split('/index')[0];
    const {
      selectedRowKeys,
      stepsList,
      MAIL_OBJ,
      signMethod,
      labourList,
      stateMap,
      issFlagMap,
      modalVisibleRemark,
      modalVisible,
      tabList,
    } = this.state;
    const { activeKey, pageData, loading, dictCode, formFieldsValue } = this.props;
    const total = pageData && pageData.pagination.total;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: (rows, selectedRows) => {
        this.setState({ selectedRowKeys: rows, selectedRows });
      },
    };

    // 待签订的表格数据
    const waitForSignColumns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 170 } }),
        render: (text, record) => {
          if (record.delayFlag && record.delayFlag === 1) {
            // 待续签
            return (
              <div>
                {(text && text) || '--'}
                <span
                  style={{
                    marginTop: '1px',
                    marginLeft: '-10px',
                    border: '1px solid red',
                    width: '64px',
                    color: 'red',
                    borderRadius: '4px',
                    fontSize: '16px',
                    WebkitTextSizeAdjust: 'none',
                    display: 'inline-block',
                    transform: 'scale(0.5)',
                    textAlign: 'center',
                  }}
                >
                  逾期
                </span>
              </div>
            );
          }
          return <span>{(text && text) || '--'}</span>;
        },
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '入职日期',
        dataIndex: 'entryDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : null),
      },
      {
        title: '合同签署方',
        dataIndex: 'contSignWayName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '办理人',
        dataIndex: 'tskName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      // {
      //   title: '服务类型',
      //   dataIndex: 'serTypeName',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      // },
      {
        title: '合同状态',
        dataIndex: 'contStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        sorter: (a, b) => a.contState - b.contState,
        render: (text, record) => (
          <Badge key={record.contState} status={stateMap[record.contState]} text={text} />
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            {record.contState === 1 ? (
              <Authorized authority="business:laborCont:signLaborCont" noMatch={null}>
                <a onClick={() => this.isSignPage(record)}>签订</a>
                <Divider type="vertical" />
              </Authorized>
            ) : (
              <Authorized authority="business:laborCont:signLaborCont" noMatch={null}>
                <a
                  onClick={() =>
                    router.push(
                      `${tempUrl}/renew?laborContId=${record.laborContId}&empId=${
                        record.empId
                      }&custId=${record.custId}&activeKey=${activeKey}`
                    )
                  }
                >
                  续签
                </a>
                <Divider type="vertical" />
              </Authorized>
            )}
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item key="update" onClick={() => this.handleRemarks(record.laborContId)}>
                    办理备注
                  </Menu.Item>
                  <Menu.Item
                    key="look"
                    onClick={() =>
                      router.push(
                        `${tempUrl}/detail?laborContId=${record.laborContId}&activeKey=${activeKey}`
                      )
                    }
                  >
                    查看
                  </Menu.Item>
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];

    // 已签订的表格数据
    const waitSendColumns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '办理人',
        dataIndex: 'tskName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      // {
      //   title: '合同开始日期',
      //   dataIndex: 'contBeginDate',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: text => (text ? moment(text).format('YYYY-MM-DD') : null),
      // },
      // {
      //   title: '合同结束日期',
      //   dataIndex: 'contEndDate',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: text => (text ? moment(text).format('YYYY-MM-DD') : null),
      // },
      // {
      //   title: '服务类型',
      //   dataIndex: 'serTypeName',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      // },
      {
        title: '签订类型',
        dataIndex: 'signType',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => matchDict(dictCode && dictCode.SIGN_TYPE, text),
      },
      {
        title: '发放状态',
        dataIndex: 'issFlagName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Badge key={record.issFlag} status={issFlagMap[record.issFlag]} text={text} />
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(
                  `${tempUrl}/detail?laborContId=${record.laborContId}&activeKey=${activeKey}`
                )
              }
            >
              查看
            </a>
            <Divider type="vertical" />

            <a onClick={() => this.isSignPage(record)}>变更</a>
          </span>
        ),
      },
    ];

    // 已终止的表格数据
    const SendedColumns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      // {
      //   title: '合同开始日期',
      //   dataIndex: 'contBeginDate',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: text => (text ? moment(text).format('YYYY-MM-DD') : null),
      // },
      {
        title: '合同结束日期',
        dataIndex: 'contEndDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : '--'),
      },
      // {
      //   title: '服务类型',
      //   dataIndex: 'serTypeName',
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      // },
      {
        title: '签订类型',
        dataIndex: 'signType',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => matchDict(dictCode && dictCode.SIGN_TYPE, text),
      },
      {
        title: '终止原因',
        dataIndex: 'endRsnName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(
                  `${tempUrl}/detail?laborContId=${record.laborContId}&activeKey=${activeKey}`
                )
              }
            >
              查看
            </a>
          </span>
        ),
      },
    ];

    // 表格配置：分页器
    const pagination = {
      defaultCurrent: pageData.pagination.current, // 默认当前页
      defaultPageSize: pageData.pagination.pageSize, // 默认单页条数
      current: pageData.pagination.current, // 当前页
      pageSize: pageData.pagination.pageSize, // 单页条数
      total, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onShowSizeChange: (current, size) => {
        this.searchList(this.processFormData(formFieldsValue), activeKey, current, size, undefined, false);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${pagination.current} / ${totalPage}页`;
      },
    };

    // 待签订
    const waitForSignCont = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="business:laborCont:uploadExcelSignInfo" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => router.push(`${tempUrl}/batchsign`)}
            >
              批量签订
            </Button>
          </Authorized>
          <Authorized authority="business:laborCont:expEmpCont" noMatch={null}>
            <Button icon={<DownloadOutlined />} onClick={this.export}>
              导出
            </Button>
          </Authorized>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={pageData && pageData.list}
          rowKey={record => record.laborContId}
          columns={waitForSignColumns}
          pagination={pagination}
          onChange={this.onWaitForSignContChange}
        />
      </div>
    );

    // 已签订
    const waitForIssuedCont = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Col md={12} sm={24}>
            <Authorized authority="business:laborCont:updateIssFlag" noMatch={null}>
              <Button type="primary" style={{ marginRight: 8 }} onClick={this.sendCont}>
                发放
              </Button>
            </Authorized>
            {checkPermissions('business:laborCont:updateEndLabor') && (
              <Button onClick={this.termination} style={{ marginRight: 8 }}>
                终止
              </Button>
            )}
            {checkPermissions('business:laborCont:expEmpCont') && (
              <Button onClick={this.export}>导出</Button>
            )}
          </Col>
          <Col md={5} sm={24} offset={7}>
            <RadioGroup defaultValue="null" onChange={this.searchAll} style={{ float: 'right' }}>
              <RadioButton value="null">全部</RadioButton>
              <RadioButton value="2">未发放</RadioButton>
              <RadioButton value="1">已发放</RadioButton>
            </RadioGroup>
          </Col>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={pageData && pageData.list}
          rowKey={record => record.laborContId}
          columns={waitSendColumns}
          pagination={pagination}
          onChange={this.onWaitForSignContChange}
        />
      </div>
    );

    // 已终止
    const terminated = (
      <div>
        <Table
          rowSelection={rowSelection}
          dataSource={pageData && pageData.list}
          rowKey={record => record.laborContId}
          columns={SendedColumns}
          pagination={pagination}
          style={{ marginTop: 10 }}
          onChange={this.onWaitForSignContChange}
        />
      </div>
    );

    // 获取页签组件
    const getTabPane = activeKey => {
      if (activeKey === 1) {
        return waitForSignCont;
      }
      if (activeKey === 2) {
        return waitForIssuedCont;
      }
      if (activeKey === 3) {
        return terminated;
      }
    };

    // 模态框配置：办理备注
    const modalConfigRemark = {
      style: { top: 240 },
      title: '办理备注',
      visible: modalVisibleRemark,
      confirmLoading: loading,
      onOk: this.submitDataRemark,
      onCancel: () => {
        this.formRef.current.resetFields(['content']);
        this.setState({ modalVisibleRemark: false, selectedRowKeys: [] });
      },
    };

    // 模态框配置：发放
    const modalConfig = {
      style: { top: 240 },
      title: '发放',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submitData,
      onCancel: () => {
        this.formRef.current.resetFields(['respDepId', 'exprsNo', 'issRemark']);
        this.setState({ modalVisible: false, selectedRowKeys: [] });
      },
    };

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
          </Card>
          <Card className={styles.tabCard}>
            <div className={styles.tableList}>
              <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
                {tabList.map((item, index) => (
                  // eslint-disable-next-line react/no-array-index-key
                  <TabPane tab={item.name} key={index+1}>
                    {getTabPane(index + 1)}
                  </TabPane>
                ))}
              </Tabs>
            </div>
            <Modal {...modalConfig}>
              <Form ref={this.formRef} initialValues={{issWay:signMethod}}>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="发放对象" name="respDepId" rules={[{ required: modalVisible, message: '请选择' }]}>
                  <CheckboxGroup options={getcheckboxList(MAIL_OBJ)} />
                </FormItem>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="发放方式" name="issWay" rules={[{ required: true, message: '请选择'}]}>
                  <Radio.Group onChange={this.changeSignMethod}>
                    {labourList &&
                        labourList.map(options => (
                          <Radio key={options.itemCode} value={options.itemCode}>
                            {options.itemName}
                          </Radio>
                        ))}
                  </Radio.Group>
                </FormItem>
                {signMethod === '2' ? (
                  <FormItem
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 15 }}
                    label="快递单号"
                    name="exprsNo"
                    rules={[
                    {
                      required: modalVisible,
                      message: '最大长度不超过14的数字与字母组合',
                      pattern: /^[A-Za-z0-9]{1,14}$/,
                    },
                  ]}
                  >
                    <Input placeholder="请输入" />
                  </FormItem>
                ) : null}
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="备注" name="issRemark" rules={[{ required: false, message: '请输入的内容必须在1-200个字' }]}>
                  <Input placeholder="请输入" maxLength={200} />
                </FormItem>
              </Form>
            </Modal>
            <Modal {...modalConfigRemark}>
              <Form>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="备注信息" name="content" rules={[{ required: false, message: '请选择' }]}>
                  <TextArea rows={4} maxLength={200} placeholder="请输入" />
                </FormItem>
                <div style={{ color: '#1890ff', marginLeft: 28, marginBottom: 10 }}>
                  历史记录
                  <DownOutlined />
                </div>
                <Timeline style={{ marginLeft: 95 }}>
                  {stepsList.map((item) => (
                    <Timeline.Item>
                      <p>
                        {moment(item.operTime).format('YYYY-MM-DD')}
                        <span style={{ marginLeft: 20 }}>{item.operName}</span>
                      </p>
                      <p>{item.content}</p>
                    </Timeline.Item>
                  ))}
                </Timeline>
              </Form>
            </Modal>
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default BasicList;
